package com.ruoyi.web.controller.system;

import cn.hutool.core.convert.Convert;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.business.FormulaUtils;
import com.ruoyi.system.domain.Appmanager;
import com.ruoyi.system.domain.QsTagModbusTcp;
import com.ruoyi.system.domain.Qstag;
import com.ruoyi.system.service.IAlarmtypeService;
import com.ruoyi.system.service.IAppmanagerService;
import com.ruoyi.system.service.IQstagService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * 项目首页数据展示Controller
 * 
 * @author yaozh
 * @date 2024-02-24
 */
@RestController
@RequestMapping("/system/qstaghomepage")
public class QstagHomePageParamController extends BaseController
{
    @Resource
    private IQstagService qstagService;
    @Resource
    private IAlarmtypeService alarmtypeService;
    @Resource
    private IAppmanagerService appManagerService;

    /**
     * 查询项目首页数据展示列表
     */
    @PreAuthorize("@ss.hasPermi('system:qstaghomepage:list')")
    @GetMapping("/list")
    public TableDataInfo list(Qstag qstag,@RequestParam String dbName)
    {
        List<Appmanager> appList = appManagerService.selectAppManagerListByUserAndDbName(getLoginUser(),dbName);
        if(appList == null || appList.size() == 0){
            return getDataTable(new ArrayList<>());
        }
        if(qstag != null && StringUtils.hasLength(qstag.getTagname()) && qstag.isByTagFormulaSearch()){
            List<Qstag> tempList = qstagService.selectQstagList(qstag,dbName);
            LinkedList<Long> list = new LinkedList<>();
            Map<Long,Boolean> repeatMap= new HashMap<>();
            for(Qstag tempQsTag : tempList){
                list.add(tempQsTag.getTagid());
                repeatMap.put(tempQsTag.getTagid(),true);

                String tagFormula = tempQsTag.getTagformula();
                List<String> tagFormulaList = FormulaUtils.getIdArrayOfFormula(tagFormula);
                if(tagFormulaList.size() > 0){
                    for(String idStr : tagFormulaList){
                        Long tempId = Long.parseLong(idStr);
                        Boolean find = repeatMap.get(tempId);
                        if(find == null || !find){
                            list.add(tempId);
                            repeatMap.put(tempId,true);
                        }
                    }
                }
            }
            Map<Long,Integer> map = new HashMap<>();
            if(list.size() > 0){
                Long[] tagIdArray = new Long[list.size()];
                int i = 0;
                for(Long tagId : list){
                    tagIdArray[i] = tagId;
                    map.put(tagId,i);
                    i++;
                }
                List<Qstag> theList = qstagService.selectQstagByTagidList(tagIdArray,dbName);
                Qstag[] returnArray = new Qstag[theList.size()];
                for(Qstag tempQsTag : theList){
                    int index = map.get(tempQsTag.getTagid());
                    returnArray[index] = tempQsTag;
                }
                List<Qstag> resultList = new ArrayList<>(Arrays.asList(returnArray));
                return getDataTable(resultList);
            }
        }

        startPage();
        List<Qstag> list = qstagService.selectHomepageQsTagList(dbName);
        return getDataTable(list);
    }

    /**
     * 导出项目首页数据展示列表
     */
    @PreAuthorize("@ss.hasPermi('system:qstaghomepage:export')")
    @Log(title = "项目首页数据展示", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Qstag qstag,@RequestParam String dbName)
    {
        List<Appmanager> appList = appManagerService.selectAppManagerListByUserAndDbName(getLoginUser(),dbName);
        List<Qstag> list = new ArrayList<>();
        if(appList != null && appList.size() > 0){
            list = qstagService.selectQstagList(qstag,dbName);
        }
        ExcelUtil<Qstag> util = new ExcelUtil<Qstag>(Qstag.class);
        util.exportExcel(response, list, "项目首页数据展示数据");
    }

    @Log(title = "项目首页数据展示", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('system:qstaghomepage:import')")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport, @RequestParam String dbName) throws Exception
    {
        ExcelUtil<Qstag> util = new ExcelUtil<Qstag>(Qstag.class);
        List<Qstag> qsTagList = util.importExcel(file.getInputStream());
        String operName = getUsername();
        String message = qstagService.importQsTag(qsTagList, updateSupport, operName, dbName);
        return success(message);
    }

    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response)
    {
        ExcelUtil<QsTagModbusTcp> util = new ExcelUtil<QsTagModbusTcp>(QsTagModbusTcp.class);
        util.importTemplateExcel(response, "全新点表初始化项目的数据");
    }

    /**
     * 获取项目首页数据展示详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:qstaghomepage:query')")
    @GetMapping(value = "/{tagid}")
    public AjaxResult getInfo(@PathVariable("tagid") Long tagid,@RequestParam String dbName)
    {
        return success(qstagService.selectQstagByTagid(tagid,dbName));
    }

    /**
     * 新增项目首页数据展示
     */
    @PreAuthorize("@ss.hasPermi('system:qstaghomepage:add')")
    @Log(title = "项目首页数据展示", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Qstag qstag,@RequestParam String dbName)
    {
        return toAjax(qstagService.insertQstag(qstag,dbName));
    }

    /**
     * 修改项目首页数据展示
     */
    @PreAuthorize("@ss.hasPermi('system:qstaghomepage:edit')")
    @Log(title = "项目首页数据展示", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Qstag qstag,@RequestParam String dbName)
    {
        return toAjax(qstagService.updateQstag(qstag,dbName));
    }

    /**
     * 删除项目首页数据展示
     */
    @PreAuthorize("@ss.hasPermi('system:qstaghomepage:remove')")
    @Log(title = "项目首页数据展示", businessType = BusinessType.DELETE)
	@DeleteMapping("/{tagids}")
    public AjaxResult remove(@PathVariable Long[] tagids,@RequestParam String dbName)
    {
        return toAjax(qstagService.deleteQstagByTagids(tagids,dbName));
    }

    /**
     * 不分页，查询驱动列表
     */
    @PreAuthorize("@ss.hasPermi('system:qstaghomepage:list')")
    @GetMapping("/listAllAlarmType")
    public AjaxResult listAll(@RequestParam String dbName)
    {
        List<Appmanager> appList = appManagerService.selectAppManagerListByUserAndDbName(getLoginUser(),dbName);
        if(appList == null || appList.size() == 0){
            return success(new ArrayList<>());
        }
        return success(alarmtypeService.selectAlarmtypeForAll(dbName));
    }

}
